package com.itheima.reggie.controller;

import com.itheima.reggie.common.R;
import com.itheima.reggie.entity.ShoppingCart;
import com.itheima.reggie.service.ShoppingCartService;
import org.apache.ibatis.annotations.Delete;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RequestMapping("/shoppingCart")
@RestController
public class ShoppingCartController {
    
    @Autowired
    private ShoppingCartService cartService;
    
    /**
     * 清空购物车
     * @return
     */
    @DeleteMapping("/clean")
    public R clean(){
        //1. 调用service
        int row = cartService.clean();
        
        //2. 判断结果
        if(row > 0 ){
            return R .success("清空购物车成功");
        }else{
            return R .error("清空购物车失败");
        }
    }
    
    /**
     * 查看购物车数据
     */
    @GetMapping("/list")
    public R list(){
    
        try {
            //1. 调用service
            List<ShoppingCart> list = cartService.list();
            return R.success(list);
        } catch (Exception e) {
            e.printStackTrace();
            return R.error("查询购物车失败！");
        }
    
    }
    
    /**
     * 加入购物车
     * @param shoppingCart
     * @return
     */
    @PostMapping("/add")
    public R add(@RequestBody ShoppingCart shoppingCart){
    
        try {
            //1. 调用service
            ShoppingCart sc = cartService.add(shoppingCart);
        
            //2. 返回结果。
            return R.success(sc);
        } catch (Exception e) {
            e.printStackTrace();
            return R.error("添加购物车失败！");
        }
    
    }
}
